import json
import threading
import queue

from app import services
from mqtt.data_parse import DataParse
from mqtt.mqtt_manage import message_queue


class MessageHandler(threading.Thread):
    msgQueue = queue.Queue()
    data_parser = DataParse()

    def __init__(self, msgQueue):
        super().__init__()
        self.msgQueue = msgQueue

    def run(self):
        while True:
            if not message_queue.empty():
                # print("队列中的元素个数:", message_queue.qsize())
                result = message_queue.get()
                # print(result)
                # 进一步解析数据 解析第二个json 看是不是我们定义的 如果是 分别插入对应的model数据库中
                # resutlMap = json.loads(result)

                sn_id = result['sn_id']
                if not sn_id == "7CDFA1D0A90E":
                    continue
                print(sn_id)
                powerData = None
                bmsData = None
                powerSystem = None

                for key, value in result.items():
                    if key == 'power_grid_data':
                        powerData = self.data_parser.parsePowerData(value)
                    if key == 'bms_data':
                        bmsData = self.data_parser.parseBMSData(value)
                    if key == 'battery_normal_data':
                        powerSystem = self.data_parser.parseSystemData(value)

                if powerData is not None:
                    print("更新数据表")
                    powerData.sn_id = sn_id
                    services.updatePowerGridData(powerData)
                if bmsData is not None:
                    print("更新bms_data")
                    bmsData.sn_id = sn_id
                    services.updateBmsData(bmsData)
                if powerSystem is not None:
                    print("更新powerSystem")
                    powerSystem.sn_id = sn_id
                    services.updateSystemData(powerSystem)
                # print(result)
